package com.cai.baselibrary.net.intercepto

import android.text.TextUtils
import android.util.Log
import com.blankj.utilcode.util.LogUtils
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.Response
import okhttp3.ResponseBody

/**Log日志拦截器*/
class LoggerInterceptor constructor(tag:String,showResponse:Boolean): Interceptor {
    constructor(tag:String):this(tag,false)

    private val TAG: String = tag//日志标记
    private val isResponse = showResponse//是否显示(数据内容)


    override fun intercept(chain: Interceptor.Chain): Response {
        return logForResponse(chain.proceed(chain.request()))
    }


    private fun logForResponse(response: Response): Response {
        try {
            //===>response log
            LogUtils.e(TAG, "========response'log=======")
            val builder = response.newBuilder()
            val clone = builder.build()
            LogUtils.e(TAG, "url : " + clone.request().url())
            LogUtils.e(TAG, "code : " + clone.code())
            LogUtils.e(TAG, "protocol : " + clone.protocol())
            if (!TextUtils.isEmpty(clone.message())) LogUtils.e(TAG, "message : " + clone.message())
            if (isResponse) {
                var body = clone.body()
                if (body != null) {
                    val mediaType = body.contentType()
                    if (mediaType != null) {
                        LogUtils.e(TAG, "responseBody's contentType : $mediaType")
                        if (isText(mediaType)) {
                            val resp = body.string()
                            LogUtils.e(TAG, "responseBody's content : $resp")
                            body = ResponseBody.create(mediaType, resp)
                            return response.newBuilder().body(body).build()
                        } else {
                            LogUtils.e(
                                TAG,
                                "responseBody's content : " + " maybe [file part] , too large too print , ignored!"
                            )
                        }
                    }
                }
            }
            LogUtils.e(TAG, "========response'log=======end")
        } catch (e: Exception) {
//            e.printStackTrace();
        }
        return response
    }


    private fun isText(mediaType: MediaType): Boolean {
        if (mediaType.type() != null && mediaType.type() == "text") {
            return true
        }
        if (mediaType.subtype() != null) {
            if (mediaType.subtype() == "json" || mediaType.subtype() == "xml" || mediaType.subtype() == "html" || mediaType.subtype() == "webviewhtml") return true
        }
        return false
    }

}